import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @projectName: java-daily-questions
 * @package: PACKAGE_NAME
 * @className: ParkingLotThread
 * @author: ZM
 * @description: 模拟停车场 车位
 * @date: 2021/8/26 13:02
 * @version: 1.0
 */
public class ParkingLotThread {

    public static void main(String[] args) {
        // 模拟 100个车位
        Semaphore space = new Semaphore(100);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 入口
        new Thread(() -> {
            while (true) {
                try {
                    if (space.availablePermits() > 0) {
                        space.acquire(1);
                        System.out.println(format.format(new Date()) + "  一辆车入驻，现有车位：" + space.availablePermits());
                        Thread.sleep(new Random().nextInt(100));
                    } else {
                        System.out.println("车位不足！！！");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 出口
        new Thread(() -> {
            while (true) {
                try {
                    if (space.availablePermits() < 100) {
                        space.release(1);
                        System.out.println(format.format(new Date()) + "  一辆车驶出停车场，现有车位：" + space.availablePermits());
                        Thread.sleep(new Random().nextInt(100));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }
}
